package com.htc.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

/**
 * @author: htc
 * @date: Created in 10:44 2018/5/15.
 */
@Configuration
@EnableJpaRepositories(basePackages = "com.htc.repository")
@EnableTransactionManagement
public class JpaConfig {
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 设置实体类的管理工厂
     * @return
     */
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        HibernateJpaVendorAdapter jpaVendor =new HibernateJpaVendorAdapter();
        //设置是否生成SQL
        jpaVendor.setGenerateDdl(false);

        //实例化实体映射管理工厂类
        LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
        //设置数据源
        entityManagerFactory.setDataSource(dataSource());
        //设置jpa适配器
        entityManagerFactory.setJpaVendorAdapter(jpaVendor);
        //设置实体类包名
        entityManagerFactory.setPackagesToScan("com.htc.entity");

        return entityManagerFactory;
    }

    /**
     * 事务管理类
     */
    @Bean
    public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory){
        JpaTransactionManager transactionManager =new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }

}
